package com.qf.smsplatform.strategy.service.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.index.StandardSubmit;
import com.qf.smsplatform.strategy.api.CacheService;
import com.qf.smsplatform.strategy.service.FilterChain;
import com.qf.smsplatform.strategy.service.StrategyManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;


@Service
@Slf4j
public class StrategyManagerImpl implements StrategyManager {

    @Resource
    private CacheService cacheService;

    private  final  String FIELD = "filters";


    @Autowired           //泛型注入
    private Map<String, FilterChain> strategyFilter;
    @Override
    public void execute(StandardSubmit submit) {

        //并且以一定的顺序去执行
        //生成一个全局唯一的id
        //获取到全部的过滤器链
        log.info("【策略过滤器链Manager】  strategyFilter = {}",strategyFilter);
        //Redis中获取"black,dirtyWords,limit,mobilePhase,fee,router"

       Long squence = cacheService.incr(CacheConstants.CACHE_PREFIX_SMS_SEQUENCE + submit.getClientID(),1L);

       submit.setSequenceld(submit.getClientID() + " " + squence);
    //从redis中获取执行顺序
        String filters = cacheService.hGet(CacheConstants.CACHE_PREFIX_CLIENT+ submit.getClientID(),FIELD);
        //将顺序以逗号分隔
        if (!StringUtils.isEmpty(filters)){
            String[] filterArray = filters.split(",");


            //遍历filters的数组
            for (String filter : filterArray) {

                //通过strategyfilters的map集合，获取指定的filterchain
                FilterChain filterChain = strategyFilter.get(filter);
                boolean strategy = filterChain.strategy(submit);
                //判断，返回结果Wiefalse直接调用结束

                if (!strategy){
                    break;
                }
            }







        }

    }
}
